package gui.productgroup;

import gui.common.*;
import core.CoreFacade;
import core.ProductContainer;
import core.Unit;
import gui.inventory.*;

/**
 * Controller class for the add product group view.
 */
public class AddProductGroupController extends Controller implements
		IAddProductGroupController {
	
	private CoreFacade core;
	private boolean canAdd;
	private String nameToAdd, valueToAdd;
	private SizeUnits unitToAdd;
	private ProductContainer parent;
	
	/**
	 * Constructor.
	 * 
	 * @param view Reference to add product group view
	 * @param container Product container to which the new product group is being added
	 */
	public AddProductGroupController(IView view, ProductContainerData container) {
		super(view);		
		core = CoreFacade.getInstance();
		
		parent = (ProductContainer)container.getTag();
		getView().setSupplyValue("0");
		getView().setSupplyUnit(SizeUnits.Count);
		
		construct();
	}

	//
	// Controller overrides
	//
	
	/**
	 * Returns a reference to the view for this controller.
	 * 
	 * {@pre None}
	 * 
	 * {@post Returns a reference to the view for this controller.}
	 */
	@Override
	protected IAddProductGroupView getView() {
		return (IAddProductGroupView)super.getView();
	}

	/**
	 * Sets the enable/disable state of all components in the controller's view.
	 * A component should be enabled only if the user is currently
	 * allowed to interact with that component.
	 * 
	 * {@pre None}
	 * 
	 * {@post The enable/disable state of all components in the controller's view
	 * have been set appropriately.}
	 */
	@Override
	protected void enableComponents() 
	{
		getView().enableOK(canAdd);
	}

	/**
	 * Loads data into the controller's view.
	 * 
	 *  {@pre None}
	 *  
	 *  {@post The controller has loaded data into its view}
	 */
	@Override
	protected void loadValues() 
	{
		//This will need to load what value?
	}

	//
	// IAddProductGroupController overrides
	//

	/**
	 * This method is called when any of the fields in the
	 * add product group view is changed by the user.
	 */
	@Override
	public void valuesChanged() 
	{
		nameToAdd = getView().getProductGroupName();
		unitToAdd = getView().getSupplyUnit();
		valueToAdd = getView().getSupplyValue();
		float value;
		try{
			value = Float.parseFloat(valueToAdd);
		} catch (Exception e){
			value = -1;
		}
		canAdd = core.canAddProductGroup(parent, nameToAdd, value, unitToAdd.toUnit());
		enableComponents();
	}

	
	/**
	 * This method is called when the user clicks the "OK"
	 * button in the add product group view.
	 */
	@Override
	public void addProductGroup() 
	{
		float value = Float.parseFloat(valueToAdd);
		try{
			core.addProductGroup(parent, nameToAdd, value, unitToAdd.toUnit());
		}
		catch(Exception e)
		{
			// what do we do with these?
		}
	}

}

